﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragCondiment : EventBehaviour {
    public enum CondimentType {
        Common,
        Single,
        Multi,
    }

    public CondimentType type;
    public float height = 0.5f;
    public float radius = 0.1f;
    public new CondimentName name;
    public GameObject vfx;
    public Transform cube;

    Transform _transform;
    Vector3 _screenPos;
    Vector3 _originPos;
    Camera _camera;
    bool _canFalling;
    bool _canRotate;
    Rigidbody _rigidbody;

    static Transform _triggerTarget;
    static List<CondimentName> _hasPlayedVoices;

    void Start() {
        _transform = GetComponent<Transform>();
        _camera = _transform.root.GetComponentInChildren<Camera>();
        _originPos = _transform.position;
        _rigidbody = GetComponent<Rigidbody>();

        _hasPlayedVoices = new List<CondimentName>();

        if (type != CondimentType.Common) {
            _rigidbody.isKinematic = false;
        } else {
            cube = _transform.Find("Cube");
        }
    }

    void OnTriggerEnter(Collider other) {
        if (other.name != "Collider") {
            _canFalling = false;
            _canRotate = false;
            OnUpdate();
            return;
        }

        if (type == CondimentType.Common) {
            _canRotate = true;     
        } else  {
            _canFalling = true;
        }

        OnUpdate();
    }

    void OnTriggerStay(Collider other) {
        if (other.name != "Collider") {
            return;
        }

        if (type == CondimentType.Common) {
            _canRotate = true;
        }

        OnUpdate();
    }

    void OnTriggerExit(Collider other) {
        if (other.name != "Collider") {
            return;
        }

        if (type == CondimentType.Common) {
            _canRotate = false;
        } else {
            _canFalling = false;
        }

        OnUpdate();
    }

    void OnUpdate() {
        if (type != CondimentType.Common) {
            return;
        }

        if (_canRotate) {
            var angle = (name == CondimentName.Sauce) ? 120f : 150f;
            _transform.DOLocalRotate(Vector3.forward * angle, 0.3f).OnComplete(() => {
                cube.SetActive(true);

                if (_canFalling) {
                    _playSFX = true;
                    PlaySFX();

                    // 播放特效
                    if (vfx) {
                        PlayVFX(true);
                    }
                }
            });

            PlaySFX();
        } else {
            // 停止特效
            _playSFX = false;

            if (vfx) {
                PlayVFX(false);
            }

            if (_gas != null) {
                _gas.Stop();
            }

            _transform.DOLocalRotate(Vector3.forward * 0f, 0.3f).OnComplete(() => cube.SetActive(false));
        }
    }

    public void SetFallingState(bool isCan) {
        _canFalling = isCan;
        OnUpdate();
    }

    List<Rigidbody> _rbList = new List<Rigidbody>();

    public override void OnBeginDrag(PointerEventData eventData) {
        switch (type) {
            case CondimentType.Common:
                
                break;
            case CondimentType.Multi:
                Collider[] colliders = Physics.OverlapSphere(_transform.position, radius);

                foreach (Collider hit in colliders) {
                    Rigidbody rb = hit.GetComponent<Rigidbody>();

                    if (rb) {
                        rb.isKinematic = true;
                        rb.transform.SetParent(_transform);
                        _rbList.Add(rb);
                    }
                }
                break;
            case CondimentType.Single:
                if (_rigidbody) {
                    _rigidbody.isKinematic = true;
                }
                break;
        }

        _screenPos = _camera.WorldToScreenPoint(_transform.position + (Vector3.up * height));

        if (_triggerTarget == null) {
            _triggerTarget = FindObjectOfType<ForceController>().transform.Find("Collider");
        }

        _triggerTarget.SetActive(true);

        if (!_hasPlayedVoices.Contains(name)) {
            var path = ChineseRestaurantManager.Instance.GetVoicePathFrom(name);
            AudioManager.Instance.PlaySound(path);
            _hasPlayedVoices.Add(name);
        }
    }

    GameAudioSource _gas;
    bool _playSFX;

    public override void OnDrag(PointerEventData eventData) {
        var mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, _screenPos.z);
        var worldPos = _camera.ScreenToWorldPoint(mousePos);
        _transform.position = worldPos;
    }

    void PlaySFX() {
        if (_playSFX) {
            if (name == CondimentName.Sauce) {

            } else {
                if (_gas == null || !_gas.IsPlaying) {
                    _gas = AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_CHICKEN_SALT, true);
                }
            }
        }
    }

    void PlayVFX(bool isPlay) {
        var vfxs = vfx.transform.GetComponentsInChildren<ParticleSystem>();

        foreach (var fx in vfxs) {
            var emit = fx.emission;
            emit.enabled = isPlay;
        }

        if (name == CondimentName.Sauce) {
            if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {
                FindObjectOfType<StockpotController>().SetWaterColor(isPlay);
            } else {
                FindObjectOfType<PanController>().SetOilColor(isPlay);
            }
        }

        if (isPlay) {
            LevelSecond.Instance.ShowConfirmButton();
        }
    }

    public override void OnEndDrag(PointerEventData eventData) {
        _triggerTarget.SetActive(false);

        switch (type) {
            case CondimentType.Common:
                // 停止特效
                _playSFX = false;
                _canFalling = false;

                if (vfx) {
                    PlayVFX(false);
                }

                if (_gas != null) {
                    _gas.Stop();
                }

                _transform.DOLocalRotate(Vector3.forward * 0f, 0.3f).OnComplete(() => _transform.DOMove(_originPos, 0.3f));
                break;
            case CondimentType.Multi:
                if (_canFalling) {
                    foreach (var rb in _rbList) {
                        rb.transform.SetParent(_triggerTarget.parent);
                        rb.isKinematic = false;
                        rb.GetComponent<Collider>().material = ChineseRestaurantManager.Instance.PhysicMat;

                        if (ChineseRestaurantManager.Instance.currentDishName != DishName.QingCaiDouFuTang && !SwitchController.IsOn) {
                            rb.mass = 0.1f;
                        }
                        
                        StartCoroutine(TimeUtility.DelayInvoke(0.5f, () => {
                            rb.mass = 1f;

                            if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {
                                var fbp = rb.gameObject.AddComponent<FloaterByPhysics>();
                                fbp.waterLevel = 1.36f;

                                if (SwitchController.IsOn) {
                                    fbp.enabled = false;
                                }

                                ChineseRestaurantManager.Instance.FloaterList.Add(fbp);
                            }

                            Destroy(rb.GetComponent<DragCondiment>());
                        }));
                    }

                    _rbList.Clear();
                    SplashFX.ShowSplash = true;

                    if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {
                        AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_CONDIMENT_FALLING_WATER);
                        FindObjectOfType<StockpotController>().waterRenderer.GetComponent<Collider>().enabled = true;
                    }

                    LevelSecond.Instance.ShowConfirmButton();
                } else {
                    _transform.DOMove(_originPos + (Vector3.up * 0.2f), 0.5f).OnComplete(() => {
                        foreach (var rb in _rbList) {
                            rb.transform.SetParent(_transform.parent);
                            rb.isKinematic = false;
                        }

                        _rbList.Clear();
                    });
                }
                break;
            case CondimentType.Single:
                if (_canFalling) {
                    if (_rigidbody) {
                        _transform.SetParent(_triggerTarget.parent);
                        _rigidbody.isKinematic = false;
                        _transform.DOScale(Vector3.one * 0.5f, 0.5f);
                        GetComponent<Collider>().material = ChineseRestaurantManager.Instance.PhysicMat;

                        SplashFX.ShowSplash = true;

                        if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {
                            AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_CONDIMENT_FALLING_WATER);
                            FindObjectOfType<StockpotController>().waterRenderer.GetComponent<Collider>().enabled = true;
                        }

                        LevelSecond.Instance.ShowConfirmButton();
                        Destroy(this);
                    }
                } else {
                    _transform.DOMove(_originPos + (Vector3.up * 0.2f), 0.5f).OnComplete(() => {
                        if (_rigidbody) {
                            _rigidbody.isKinematic = false;
                        }
                    });
                }
                break;
        }
        
    }
}
